//DESCRIPTION:将选区内所有线条(GraphicLine)应用为指定对象样式
#target "indesign"
(function () {
    if (app.documents.length === 0) { alert("请先打开一个文档。"); return; }
    if (app.selection.length === 0) { alert("请先选择对象（可包含编组或未编组对象）。"); return; }

    var doc = app.activeDocument;

    // ===== 收集对象样式（含组路径）=====
    function collectObjectStyles() {
        var names = [];
        var map   = {}; // fullPath -> ObjectStyle
        function walkGroup(container, prefix) {
            // 样式本身
            var styles = container.objectStyles;
            for (var i = 0; i < styles.length; i++) {
                var st = styles[i];
                // 可选：排除 [Normal Object Style]，若想显示也可去掉判断
                // if (st.name === "[Normal Object Style]") continue;
                var full = prefix ? (prefix + "/" + st.name) : st.name;
                names.push(full);
                map[full] = st;
            }
            // 子组
            var grps = container.objectStyleGroups;
            for (var j = 0; j < grps.length; j++) {
                var g = grps[j];
                var newPrefix = prefix ? (prefix + "/" + g.name) : g.name;
                walkGroup(g, newPrefix);
            }
        }
        walkGroup(doc, ""); // 从文档根开始
        names.sort(function(a,b){ return a.toUpperCase()<b.toUpperCase()?-1:(a.toUpperCase()>b.toUpperCase()?1:0); });
        return {list:names, map:map};
    }

    var stylesInfo = collectObjectStyles();
    if (stylesInfo.list.length === 0) { alert("此文档没有可用的对象样式。"); return; }

    // ===== 简单选择对话框 =====
    var w = new Window("dialog", "选择要应用的对象样式（仅作用于选区内的线条）");
    w.orientation = "column";
    w.alignChildren = ["fill","top"];

    var p = w.add("panel", undefined, "对象样式");
    p.margins = [10,20,10,10];
    p.alignChildren = ["fill","top"];

    var dd = p.add("dropdownlist", undefined, stylesInfo.list);
    dd.minimumSize.width = 360;
    dd.selection = 0;

    var gBtns = w.add("group"); gBtns.alignment = ["right","top"];
    var btnCancel = gBtns.add("button", undefined, "取消");
    var btnOK     = gBtns.add("button", undefined, "确定", {name:"ok"});
    btnCancel.onClick = function(){ w.close(0); };
    btnOK.onClick = function(){
        if (!dd.selection) { alert("请选择一个对象样式"); return; }
        w.close(1);
    };
    if (w.show() !== 1) return;

    var chosenName  = stylesInfo.list[dd.selection.index];
    var chosenStyle = stylesInfo.map[chosenName];
    if (!chosenStyle || !chosenStyle.isValid) { alert("所选对象样式无效。"); return; }

    // ===== 统计 & 执行（一次性撤销）=====
    var stats = { collected: 0, applied: 0, skippedLocked: 0, errors: 0 };

    app.doScript(function () {
        // 收集选区中的所有 GraphicLine
        var lines = collectGraphicLinesFromSelection(app.selection);
        stats.collected = lines.length;

        for (var i = 0; i < lines.length; i++) {
            var ln = lines[i];
            try {
                if (!ln || !ln.isValid) continue;
                if (ln.locked || (ln.itemLayer && ln.itemLayer.locked)) { stats.skippedLocked++; continue; }

                ln.appliedObjectStyle = chosenStyle;
                stats.applied++;
            } catch (e) {
                stats.errors++;
            }
        }
    }, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "将线条应用对象样式");
/*
    alert(
        "已选择样式： " + chosenName +
        "\n选区内线条总数： " + stats.collected +
        "\n已应用样式： " + stats.applied +
        "\n跳过（锁定/锁层）： " + stats.skippedLocked +
        "\n出错： " + stats.errors
    );
*/
    // ===== 工具：从当前选区收集 GraphicLine =====
    function collectGraphicLinesFromSelection(selArr) {
        var out = [], seen = {};
        for (var i = 0; i < selArr.length; i++) {
            addFromItem(selArr[i], out, seen);
        }
        return out;
    }
    function addFromItem(item, out, seen) {
        if (!item || !item.isValid) return;

        // 自身就是线条
        if (item.constructor && item.constructor.name === "GraphicLine") {
            var id = item.id;
            if (!seen[id]) { seen[id] = true; out.push(item); }
        }

        // 容器：allPageItems 会抓到后代（包含嵌套组/锚定）
        try {
            if (item.allPageItems && item.allPageItems.length > 0) {
                var kids = item.allPageItems;
                for (var k = 0; k < kids.length; k++) {
                    var it = kids[k];
                    if (!it || !it.isValid) continue;
                    if (it.constructor && it.constructor.name === "GraphicLine") {
                        var kidId = it.id;
                        if (!seen[kidId]) { seen[kidId] = true; out.push(it); }
                    }
                }
            }
        } catch(_){}
    }
})();
